package com.googlecode.cswish.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


public class CssStyle {
	
	private String label;		// group
	
	private Map<String, String> styles = new LinkedHashMap<>();
	
	public String getLabel() {
		return label;
	}

	public void setLabel(String label) {
		this.label = label;
	}

	public String get(String key) {
		return styles.get(key);
	}
	
	public <T> T get(String key, Class<T> type) {
		String value = get(key);
		if (value == null) {
			return null;
		}
		
		if (type.isAssignableFrom(Integer.class)) {
			int i, len;
			for (i = 0, len = value.length(); i < len; i++) {
				char c = value.charAt(i);
				if (!Character.isDigit(c)) {
					break;
				}
			}
			return (T)new Integer(value.substring(0, i));
		} else if (type.isAssignableFrom(String.class)) {
			return (T)value;
		} else {
			// TODO: support more types
			return null;
		}
	}
	
	public void set(String key, String value) {
		add(key, value);
	}
	
	public void remove(String key) {
		styles.remove(key);
	}
	
	public void add(String key, String value) {
		styles.put(key, value);
	}
	
	public Collection<Entry<String, String>> getStyleEntry() {
		return styles.entrySet();
	}

	// TODO: Move this method to service?
	public List<KeyValue> getStyles() {
		List<KeyValue> list = new ArrayList<>();
		for (Entry<String, String> entry : getStyleEntry()) {
			KeyValue kv = new KeyValue();
			String fKey = formatName(entry.getKey());
			kv.put("name", "prop.styleMap." + fKey);		// see method 'PageService.submitCssStyle'
			kv.put("label", entry.getKey());
			kv.setValue(entry.getValue());
			list.add(kv);
		}
		return list;
	}
	
	private String formatName(String cssProperty) {
		int index = cssProperty.indexOf('-');
		if (index == -1) {
			return cssProperty;
		} else {
			int len = cssProperty.length();
			StringBuilder sb = new StringBuilder(len);
			int lastIndex = 0;
			
			while (index != -1) {
				sb.append(cssProperty.substring(lastIndex, index));
				sb.append(Character.toUpperCase(cssProperty.charAt(index + 1)));
				lastIndex = index + 2;
				index = cssProperty.indexOf('-', lastIndex);
			}
			sb.append(cssProperty.substring(lastIndex));
			
			return sb.toString();
		}
	}
	
	public void setStyleMap(Map<String, String> styleMap) {
		this.styles = styleMap;
	}
	
	public Map<String, String> getStyleMap() {
		return this.styles;
	}

	public String toString() {
		StringBuilder sb = new StringBuilder();
		for (Entry<String, String> keyValue : styles.entrySet()) {
			sb.append(keyValue.getKey()).append(':').append(keyValue.getValue()).append(';');
		}
		return sb.toString();
	}
}